//
//  LocationViewController.m
//  Travel
//
//  Created by lanou on 15/9/20.
//  Copyright (c) 2015年 TeamThree. All rights reserved.
//

#import "LocationViewController.h"
#import "LORequestManger.h"
#import "LocationModel.h"
#import "PathView.h"
#import "DetailCollectionViewCell.h"
#import "LocationCollectionReusableView.h"
#import "StrategyModel.h"
#import "StrategyAnotherDetailViewController.m"
#define kPicHeight 300.0 / 667 * kHeight
#define kAutoWidth 375 * kWidth
#define kAutoHight 667 * kHeight
#define kLocationUrl @"http://app6.117go.com/demo27/php/stickerAction.php?start=&length=12&submit=getSceneryHome&sceneryid=%@&v=i6.4.2&vc=AppStore&vd=b3c1b4cf8b498fb8&lang=zh-Hans&verify=024bb6753df57af7ba6df739621ae0a0"
#define kLocationCountry @"http://app6.117go.com/demo27/php/discoverAction.php?start=&length=12&submit=localityHome6_2&locid=%@&v=i6.4.2&vc=AppStore&vd=b3c1b4cf8b498fb8&lang=zh-Hans&verify=144629fa99d7f149d9082d1f6a747eff"
#define kStrategyUrl @"http://app6.117go.com/demo27/php/discoverAction.php?start=&subtype=-1&length=21&submit=getSceneryTours&sceneryid=%@&v=i6.4.2&vc=AppStore&vd=b3c1b4cf8b498fb8&lang=zh-Hans&verify=26e23ba17852e6f38a9db4dcc5db0801"
#define kStrategy2Url @"http://app6.117go.com/demo27/php/discoverAction.php?start=&subtype=-1&length=21&submit=getLocalityTours&locid=%@&v=i6.4.2&vc=AppStore&vd=b3c1b4cf8b498fb8&lang=zh-Hans&verify=1352e105ccabb70fee0447c786660da0"

@interface LocationViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate>
@property (nonatomic, retain) NSMutableArray *pathArray;  //标题下方的一排标识
@property (nonatomic, retain) UIScrollView *scrollView;
@property (nonatomic, retain) LocationModel *locationModel;
@property (nonatomic, retain) NSMutableArray *strategyDataArr;
@end

@implementation LocationViewController


- (void)dealloc
{
    [_strategyDataArr release];
    [_locationName release];
    [_model release];
    [_pathArray release];
    [_zoomImageView release];
    [_itemId release];
    [_collectionView release];
    [_scrollView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%@", _model.upid);
    self.view.backgroundColor = [UIColor colorWithRed:0.969 green:0.949 blue:0.902 alpha:1.000];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self setUpData];
    [self setUpSrategyData];

}


#pragma mark ------解析数据------

- (NSMutableArray *)pathArray {
    if (!_pathArray) {
        _pathArray = [[NSMutableArray alloc] init];
    }
    return _pathArray;
}

- (NSMutableArray *)strategyDataArr {
    if (!_strategyDataArr) {
        _strategyDataArr = [[NSMutableArray alloc] init];
    }
    return _strategyDataArr;
}
- (void)setUpSrategyData {
    if ([_model.upid isEqualToNumber:@0]) {
         NSString *url = [NSString stringWithFormat:kStrategy2Url, self.itemId];
        [LORequestManger GET:url success:^(id response) {
            NSDictionary *dict = (NSDictionary *)response;
            for (NSDictionary *dic in dict[@"obj"][@"list"]) {
                StrategyModel *model = [StrategyModel setStrategyModelWithDic:dic];
                [self.strategyDataArr addObject:model];
                [self.collectionView reloadData];
            }
            //NSLog(@"%@", dict);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@", error);
        }];
    }else{
        NSString *url = [NSString stringWithFormat:kStrategyUrl, self.itemId];
        [LORequestManger GET:url success:^(id response) {
            NSDictionary *dict = (NSDictionary *)response;
            for (NSDictionary *dic in dict[@"obj"][@"list"]) {
                StrategyModel *model = [StrategyModel setStrategyModelWithDic:dic];
                [self.strategyDataArr addObject:model];
                [self.collectionView reloadData];
            }
            //NSLog(@"%@", dict);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@", error);
        }];
        
    }
    
}


//解析热门推荐地数据
- (void)setUpData {
    if ([_model.upid isEqualToNumber:@0]) {
        NSString *url = [NSString stringWithFormat:kLocationCountry, self.itemId];
        [LORequestManger GET:url success:^(id response) {
            NSDictionary *dict = (NSDictionary *)response;
            self.locationModel = [LocationModel setModelWithDic:dict[@"obj"][@"head"][@"locality"]];
            //NSLog(@"%@", self.locationModel);
            for (NSDictionary *dic in dict[@"obj"][@"head"][@"locality"][@"path"]) {
                [self.pathArray addObject:dic[@"dispname"]];
            }
            [self setUpCollectionView];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@", error);
        }];
    }else{
        NSString *url = [NSString stringWithFormat:kLocationUrl, self.itemId];
        [LORequestManger GET:url success:^(id response) {
            NSDictionary *dict = (NSDictionary *)response;
            self.locationModel = [LocationModel setModelWithDic:dict[@"obj"][@"scenery"]];
            
            for (NSDictionary *dic in dict[@"obj"][@"scenery"][@"path"]) {
                [self.pathArray addObject:dic[@"dispname"]];
            }
            [self setUpCollectionView];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@", error);
        }];
    }
}

- (void)setUpCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(kWidth, kWidth / 1.7);
    layout.sectionInset = UIEdgeInsetsMake(10.0 / kAutoWidth, 10.0 / kAutoWidth, 69.0 / kAutoWidth, 10.0 / kAutoWidth);
    layout.minimumLineSpacing = 0;
    layout.headerReferenceSize = CGSizeMake(kWidth, 46.0 / kAutoHight);
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight) collectionViewLayout:layout];
    [layout release];
    
    _collectionView.backgroundColor = [UIColor colorWithRed:0.969 green:0.949 blue:0.902 alpha:1.000];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    //_collectionView.bounces = NO;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.contentInset = UIEdgeInsetsMake(kPicHeight, 0, 0, 0);
    
    [_collectionView registerClass:[DetailCollectionViewCell class] forCellWithReuseIdentifier:@"myCell"];
    [_collectionView registerClass:[LocationCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"myHeader"];
    
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, - kPicHeight, kWidth, kHeight + kPicHeight)];
    _scrollView.contentSize = CGSizeMake(0, kHeight);
    
    [_scrollView addSubview:_collectionView];
    _scrollView.contentInset = UIEdgeInsetsMake(kPicHeight, 0, 0, 0);
    _scrollView.delegate = self;
    
    _scrollView.contentOffset = CGPointMake(0, -kPicHeight);
    
    [self.view addSubview:_scrollView];

    
    
    _zoomImageView = [[UIImageView alloc]init];
    [_zoomImageView sd_setImageWithURL:[NSURL URLWithString:_coverPic] placeholderImage:nil];
    _zoomImageView.frame = CGRectMake(0, -kPicHeight, self.view.frame.size.width, kPicHeight);
    _zoomImageView.backgroundColor = [UIColor redColor];
    //contentMode = UIViewContentModeScaleAspectFill时，高度改变宽度也跟着改变
    _zoomImageView.contentMode = UIViewContentModeScaleAspectFill;//重点（不设置那将只会被纵向拉伸）
    [_collectionView addSubview:_zoomImageView];
    
    _locationName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];
    
    _locationName.text = self.model.name;
    _locationName.textColor = [UIColor colorWithWhite:1.000 alpha:0.860];
    _locationName.font = [UIFont boldSystemFontOfSize:21];
    [_locationName sizeToFit];
    _locationName.layer.shadowColor = [[UIColor grayColor] CGColor];
    _locationName.layer.shadowOffset = CGSizeMake(1, 1);
    _locationName.center = CGPointMake(kWidth / 2,  180.0 / kAutoHight);
    [_zoomImageView addSubview:_locationName];

    
    PathView *pathView = [[PathView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) nameArray:self.pathArray];
    CGRect rect = CGRectMake(0, 0, pathView.length, 30);
    pathView.frame = rect;
    pathView.transform = CGAffineTransformMakeScale(0.8, 0.8);
    pathView.center = CGPointMake(kWidth / 2, 220.0 / kAutoHight);
    pathView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
    [_zoomImageView addSubview:pathView];
    [pathView release];
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.strategyDataArr.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    LocationCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"myHeader" forIndexPath:indexPath];
    return headerView;
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    DetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath];
    [cell setCellWithModel:self.strategyDataArr[indexPath.row]];
    return cell;
}

//实现顶部图片放大效果
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat y = scrollView.contentOffset.y;//根据实际选择加不加上NavigationBarHight（44、64 或者没有导航条）
    if (y < -kPicHeight) {
        CGRect frame = _zoomImageView.frame;
        frame.origin.y = y;
        frame.size.height =  -y;//contentMode = UIViewContentModeScaleAspectFill时，高度改变宽度也跟着改变
        _zoomImageView.frame = frame;
    }
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    StrategyAnotherDetailViewController *strategyVC = [[StrategyAnotherDetailViewController alloc] init];
    [self.navigationController pushViewController:strategyVC animated:YES];
    [strategyVC release];
}

//
//- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
//    if (_collectionView.contentOffset.y > 0 ) {
//        [UIView animateWithDuration:0.8 animations:^{
//            [_scrollView setContentOffset:CGPointMake(0, 0)];
//        }];
//    }
//    NSLog(@"向下拖拽");
//}
//
//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
//    if (_collectionView.contentOffset.y == 0) {
//        [UIView animateWithDuration:0.8 animations:^{
//            [_scrollView setContentOffset:CGPointMake(0, -kPicHeight)];
//            _scrollView.bounces = YES;
//        }];
//        NSLog(@"到达顶点");
//    }else{
//        _scrollView.bounces = NO;
//    }
//    
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
